const cos = require('../service/tencos');
const fs = require('fs')
const axios = require('axios');
const { db } = require('../db');
const { randomString } = require('./common');
const moment = require('moment');
const { logger } = require('./serviceLogger');

exports.uploadFile = async (fileName, fileBuffer, directory) => {
    return new Promise((resolve, reject) => {
        // 获取年月日并进行拼接
        if (!directory) {
            directory = 'wxacode';
        }
        const date = new Date();
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours();
        const minute = date.getMinutes();
        const second = date.getSeconds();
        const path = `${directory}/` + year + '' + month + '' + day + '/' + fileName + '.png';
        cos.putObject({
            Bucket: 'xiaosaturn-1254446013',
            Region: 'ap-nanjing',
            Key: path,
            StorageClass: 'STANDARD',
            Body: Buffer.from(fileBuffer),
        }, (err, data) => {
            if (err) {
                console.log('上传失败', err);
                reject(err);
            } else {
                const url = 'https://image.xiaosaturn.com/' + path;
                // 这里将图片上传到wallpapers表里
                insertWallpaper(url);
                resolve(url);
            }
        })
    });
}

exports.uploadFileFromUrl = async (fileName, fileUrl, directory) => {
    const res = await axios.get(fileUrl, { 
        responseType: 'arraybuffer'
    });
    if (res) {
        const url = await this.uploadFile(fileName, res.data, directory);
        return url;
    }
    return '';
}

exports.getWBFileList = async (path) => {
    return new Promise((resolve, reject) => {
        cos.getBucket({
            Bucket: 'xiaosaturn-1254446013',
            Region: 'ap-nanjing',
            Prefix: path,
            // Delimiter: '/',
        }, (err, data) => {
            if (err) {
                reject(err)
            } else {
                resolve(data.Contents);
            }
        });
    })
}

const insertWallpaper = async (url) => {
    const randomStr = await randomString();
    const updateTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    const sql = `insert into wallpapers set imageCode=${randomStr}, created_at=${updateTime}, updated_at=${updateTime},
    downloadImageUrl=${url}, category_id=10, search_keywords='头像，卡通，唯美'`;
    db.query(sql, [], (err, results) => {
        if (err) {
            logger.error({}, {
                label: '插入到wallpapers表出错了' + JSON.stringify(err)
            })
        } else {
            logger.info({}, {
                label: '插入到wallpapers表成功，' + JSON.stringify(results)
            })
        }
    });
}

